package com.ywh.train.logic;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import tk.mystudio.ocr.OCR;

import com.ywh.train.Config;
import com.ywh.train.Constants;
import com.ywh.train.Util;
import com.ywh.train.bean.Passenger;
import com.ywh.train.bean.Result;
import com.ywh.train.bean.TrainQueryInfo;
import com.ywh.train.bean.UserInfo;
import com.ywh.train.gui.RobTicket;

public class LogicThread extends Thread {
	private UserInfo ui;
	private TrainClient client;
	private boolean isEnd = false;
	private boolean isLoginSuc = false;
	private boolean needSleep5Seconds = false;
	private RobTicket rob;
	//记录用户名，如果更改了用户名需要重新登录
	private String username = "";
	private String cookies = "";

	public LogicThread(UserInfo ui, TrainClient client, RobTicket rob, boolean isLoginSuc, String username, String cookies) {
		this.ui = ui;
		this.client = client;
		this.rob = rob;
		this.isLoginSuc = isLoginSuc;
		this.username = username;
		this.cookies = cookies;
		Constants.cookies = cookies;
	}

	public void run() {
        long beginBlackTransTime = 0l;
        long endBlackTransTime = 0l;
        long beginTime = 0l;
        long endTime = 0l;
		while (!this.isEnd) {
			Result rs = new Result();
			String randCode = null;
			String refundLogin = "N";
			String refundFlag = "Y";
			//String randErrorFocus = "focus";
			String randErrorFocus = "";
			while ((!isLoginSuc) && (!this.isEnd)) {
                this.rob.console("进入12306...");
                Map<String, String> loginOtsweb_Map = this.client.loginOtsweb();
                System.out.println("loginOtsweb_Map :" + loginOtsweb_Map.toString());
                String loginOtsweb_Map_cookies = loginOtsweb_Map.get("cookies");
                if (loginOtsweb_Map_cookies != null && !"".equals(loginOtsweb_Map_cookies)) {
                    this.cookies = loginOtsweb_Map_cookies;
            		Constants.cookies = loginOtsweb_Map_cookies;
                }
				Map<String, String> loginInit_Map = this.client.loginInit();
                System.out.println("loginInit_Map :" + loginInit_Map.toString());
                Map<String, String> init_tokenMap = this.client.querySingleInit();
                String init_tokenMap_token = init_tokenMap.get("token");
                if (init_tokenMap_token != null && !"".equals(init_tokenMap_token)) {
                    isLoginSuc = true;
                    this.rob.console("您已经登录...");
                } else {
					boolean randerr = false;
					if (randCode == null || "".equals(randCode) || rs.getMsg().contains("请输入正确的验证码！")) {
						this.rob.console("刷新验证码...");
						randCode = getRandCodeDailog(Constants.Login_Code_URL, 4);
						if (rs.getMsg().contains("请输入正确的验证码！")) {
							randerr = true;
							randErrorFocus = "focus";
						}
					}
					String loginInit_Map_refundLoginCheck = loginInit_Map.get("refundLoginCheck");
					String loginInit_Map_refundLoginChecked = loginInit_Map.get("refundLoginChecked");
					if (loginInit_Map_refundLoginCheck != null && "true".equals(loginInit_Map_refundLoginChecked)) {
						refundLogin = "Y";
					} else {
						refundLogin = "N";
					}
					this.rob.console("用户:" + this.ui.getUsername() + " 开始登录...");
					Map<String, String> loginAysnSuggestMap = this.client.loginAysnSuggest(randerr);
	                System.out.println("loginAysnSuggestMap :" + loginInit_Map.toString());
                    while (!"Y".equals(loginAysnSuggestMap.get("randError")) && !this.isEnd) {
                        loginAysnSuggestMap = this.client.loginAysnSuggest(randerr);
                        Util.waitMoment(Config.getSleepTime() / 30);
                        this.rob.reset(false);
                    }
                    if("Y".equals(loginAysnSuggestMap.get("randError"))) {
    					rs = this.client.login(this.ui.getUsername(), this.ui.getPassword(), randCode, loginAysnSuggestMap.get("loginRand"), refundLogin, refundFlag, randErrorFocus, randerr);
    					this.rob.console(rs.getMsg());
						if (rs.getState() == Result.SUCC) {
							isLoginSuc = true;
							this.username = this.ui.getUsername();
							//this.cookies = loginInit_Map.get("cookies");
							this.logCookies();
					        beginTime = System.currentTimeMillis();
						} else if (rs.getState() == Result.FAIL && rs.getMsg().contains("登录名不存在")) {
							this.rob.reset(true);
						}
                    }
				}
				this.rob.reset(false);
			}
			Map<String, String> tokenMap = null;
			beginBlackTransTime = System.currentTimeMillis();
			while ((isLoginSuc) && (!this.isEnd)) {
				if (!this.username.equals(this.ui.getUsername())) {
					this.rob.console("账号有变动，开始重新登录...");
					this.rob.getHttpClient().getConnectionManager().shutdown();
					this.rob.initNetwork();
					this.client = this.rob.getClient();
					this.cookies = "";
					Constants.cookies = "";
					isLoginSuc = false;
					break; // 跳出该层循环
				}
				randCode = null;
				TrainQueryInfo train = null;
				String leftTicketStr = "";
				String tourFlag = "dc";
				List<Passenger> passengers = null;
				if (tokenMap == null || !needSleep5Seconds) {
					if (tokenMap == null) {
						endTime = System.currentTimeMillis();
						if (endTime - beginTime < 900) {
							Util.waitMoment(900 - (endTime - beginTime)); // 此处停留1s
						}
					}
					tokenMap = this.client.querySingleInit();
				}
                if (tokenMap.get("token") == null || "".equals(tokenMap.get("token"))) {
                    this.rob.console("获取登录令牌:无效，开始重新登录...");
                    this.rob.getHttpClient().getConnectionManager().shutdown();
                    this.rob.initNetwork();
                    this.client = this.rob.getClient();
                    this.cookies = "";
					Constants.cookies = "";
                    isLoginSuc = false;
                    break; // 跳出该层循环
                }
				endBlackTransTime = System.currentTimeMillis();
				//如果查询车次大于8分钟,自动清空下黑名单(车次)
				if (endBlackTransTime - beginBlackTransTime > 8 * 60 * 1000) {
					beginBlackTransTime = System.currentTimeMillis();
					this.rob.setBlackTrainCodes("");
					this.ui.setBlackTrainCodes(this.rob.getBlackTrainCodes());
				}
				//this.logCookies();
				if (needSleep5Seconds) {
					Util.waitMoment(5000);
				} else {
					Util.waitMoment(Config.getSleepTime() / 30);
				}
				this.rob.console("正在查询车次...");
				List<TrainQueryInfo> allTrain = this.client.queryLeftTicket(this.ui.getFrom_station_telecode_name(), this.ui.getTo_station_telecode_name(), this.ui.getTrain_date(),
						this.ui.getRound_start_time_str(), this.ui.getTrain_no(), this.ui.getSeat(), this.ui.getSeattype_num());
				allTrain = Util.filterByStartEndTime(allTrain, this.ui.getBeginTime(), this.ui.getEndTime(), this.ui.getTrainCodeMatch(), this.ui.getBlackTrainCodes(), this.ui.getSeatTypes());
				String tipMsg = "您选的日期" + this.ui.getTrain_date() + "及时间段" + this.ui.getRound_start_time_str() + "，时间段" 
							+ this.ui.getBeginTime() + "点至" + this.ui.getEndTime() + "点，从" + this.ui.getFrom_station_telecode_name() + "到"
							+ this.ui.getTo_station_telecode_name() + "的可预订列车";
				if (allTrain.isEmpty()) {
					rs.setState(Result.FAIL);
					rs.setMsg("没找到" + tipMsg + "信息，重新查询...");
					this.rob.console(rs.getMsg());
                    this.rob.reset(false);
                    needSleep5Seconds = true;
					continue;
				}
				rs.setState(Result.SUCC);
				Collections.sort(allTrain, new TrainComparator());
				rs.setMsg("共找到" + tipMsg + allTrain.size() + "趟");
				this.rob.console(rs.getMsg());
				String specificTrain = this.ui.getTrain_code();
				if(specificTrain != null && !"".equals(specificTrain)) {
	                for (TrainQueryInfo tqi : allTrain) {
	                    if (tqi.getTrain_code().equalsIgnoreCase(specificTrain)) {
	                        train = tqi;
	                        if (Util.getSeatAI(train) != null && Constants.getTrainSeatName(Util.getSeatAI(train)) != null) {
	                            break;
	                        }
	                        this.rob.console("您指定的车次[" + specificTrain + "]无票！");
	                        train = null;
	                        break;
	                    }
	                }
					if (train == null) {
						this.rob.console("可预订车次中未找到您指定的车次:" + specificTrain + " 或指定的的车次无票！");
						if (Constants.ISENFORCE) {
							this.rob.console("已指定车次" + specificTrain + "，重新查询...");
		                    this.rob.reset(false);
		                    needSleep5Seconds = true;
							continue;
						}
					} else if(Constants.ISENFORCE) {
						if(Constants.TWO_SEAT.equals(this.ui.getSeat())) {
							if(Constants.getTrainSeat(train.getTwo_seat()) == 0) {
								this.rob.console("已指定车次" + specificTrain + "没有" + Constants.getTrainSeatName(Constants.TWO_SEAT) + "，重新查询...");
			                    this.rob.reset(false);
			                    needSleep5Seconds = true;
								continue;
							}
						} else if(Constants.ONE_SEAT.equals(this.ui.getSeat())) {
							if(Constants.getTrainSeat(train.getOne_seat()) == 0) {
								this.rob.console("已指定车次" + specificTrain + "没有" + Constants.getTrainSeatName(Constants.ONE_SEAT) + "，重新查询...");
			                    this.rob.reset(false);
			                    needSleep5Seconds = true;
								continue;
							}
						} else if(Constants.HARD_SLEEPER.equals(this.ui.getSeat())) {
							if(Constants.getTrainSeat(train.getHard_sleeper()) == 0) {
								this.rob.console("已指定车次" + specificTrain + "没有" + Constants.getTrainSeatName(Constants.HARD_SLEEPER) + "，重新查询...");
			                    this.rob.reset(false);
			                    needSleep5Seconds = true;
								continue;
							}
						} else if(Constants.HARD_SEAT.equals(this.ui.getSeat())) {
							if(Constants.getTrainSeat(train.getHard_seat()) == 0) {
								this.rob.console("已指定车次" + specificTrain + "没有" + Constants.getTrainSeatName(Constants.HARD_SEAT) + "，重新查询...");
			                    this.rob.reset(false);
			                    needSleep5Seconds = true;
								continue;
							}
						}
					}
				}
				train = (TrainQueryInfo) allTrain.get(0);
				this.rob.console("候选列车为:" + train.getTrain_code() + " 从[" + train.getFromStation() + train.getStartTime() + "]开往["
						+ train.getToStation() + train.getEndTime() + "]历时" + train.getLishi());

				String seatType = Util.getSeatAI(train);
				if (seatType == null || "".equals(seatType)) {
					this.rob.console("待预订的车次[" + train.getTrain_code() + "]无票！");
					// 加入黑名单
					if (!this.rob.getBlackTrainCodes().contains(train.getTrain_code())) {
						this.rob.setBlackTrainCodes(this.rob.getBlackTrainCodes() + "|" + train.getTrain_code());
						this.ui.setBlackTrainCodes(this.rob.getBlackTrainCodes());
					}
					this.rob.console("没有足够的票，加入黑名单，重新开始查询车次...");
                    this.rob.reset(false);
                    needSleep5Seconds = true;
					continue;
				}
				needSleep5Seconds = false;
				this.ui.setSeat(seatType);
				this.rob.console("候选席别为:" + Constants.getTrainSeatName(seatType));
				this.rob.console("开始预定...");
				Util.waitMoment(Config.getSleepTime() / 30);
				Map<String, String> bookMap = this.client.submutOrderRequest(this.ui.getRound_start_time_str(), this.ui.getTrain_date(), train);
				leftTicketStr = bookMap.get("leftTicketStr");
				String book_token = bookMap.get("token");
				while ((leftTicketStr == null || "".equals(leftTicketStr)) || (book_token == null || "".equals(book_token)) && (isLoginSuc) && (!this.isEnd)) {
					Util.waitMoment(Config.getSleepTime() / 30);
					bookMap = this.client.submutOrderRequest(this.ui.getRound_start_time_str(), this.ui.getTrain_date(), train);
                    leftTicketStr = bookMap.get("leftTicketStr");
					book_token = bookMap.get("token");
					if (book_token == null || "".equals(book_token)) {
						this.rob.console("获取订单令牌:无效，开始重新登录...");
						this.rob.getHttpClient().getConnectionManager().shutdown();
						this.rob.initNetwork();
						this.client = this.rob.getClient();
						this.cookies = "";
						Constants.cookies = "";
						isLoginSuc = false;
					}
					this.rob.reset(false);
				}
				if (!isLoginSuc) {
					break; // 跳出该层循环
				}
		        beginTime = System.currentTimeMillis();
				this.rob.console("剩余票信息:" + leftTicketStr);
				//this.rob.console("令牌:" + book_token);
                //this.rob.console("验证码...");
                //this.client.getCodeByte(Constants.PassCode_Randp_URL);
                this.rob.console("刷新验证码...");
                randCode = getRandCodeDailog(Constants.PassCode_Randp_URL, 4);
				this.rob.console("查询人员信息...");
				passengers = this.client.getPassengerJson();
				//first step
				this.rob.console("提交订单...");
                endTime = System.currentTimeMillis();
                if (endTime - beginTime < 9900) {
                    Util.waitMoment(9900 - (endTime - beginTime)); // 此处停留10s
                }
                this.rob.console("验证订单信息...");
				Map<String, String> checkOrderInfoMap = this.client.checkOrderInfo(randCode, book_token, this.ui, train, passengers, leftTicketStr, tourFlag);
				String checkOrderInfoMap_errMsg = checkOrderInfoMap.get("errMsg");
				String checkOrderInfoMap_msg = checkOrderInfoMap.get("msg");
				String checkOrderInfoMap_checkHuimd = checkOrderInfoMap.get("checkHuimd");
				String checkOrderInfoMap_check608 = checkOrderInfoMap.get("check608");
				while ((!"Y".equals(checkOrderInfoMap_errMsg) || "N".equals(checkOrderInfoMap_checkHuimd) || "N".equals(checkOrderInfoMap_check608)) && (isLoginSuc) && (!this.isEnd)) {
					if (!"Y".equals(checkOrderInfoMap_errMsg)) {
						this.rob.console("处理失败，原因：" + checkOrderInfoMap_errMsg);
						if(checkOrderInfoMap_errMsg != null && (checkOrderInfoMap_errMsg.contains("无票") || checkOrderInfoMap_errMsg.contains("没有足够的票"))) {
							break;
						}
						if(checkOrderInfoMap_errMsg != null && (checkOrderInfoMap_errMsg.contains("验证码错误") || checkOrderInfoMap_errMsg.contains("验证码不正确"))) {
							this.rob.console("刷新验证码...");
							randCode = getRandCodeDailog(Constants.PassCode_Randp_URL, 4);
						}
					} else if("N".equals(checkOrderInfoMap_checkHuimd)){
						// alert("对不起，由于您取消次数过多，今日将不能继续受理您的订票请求！");
						this.rob.console("处理失败，原因：" + checkOrderInfoMap_msg);
						break;
					}else if("N".equals(checkOrderInfoMap_check608)){
						// alert("本车为实名制列车，实行一日一车一证一票制！");
						this.rob.console("处理失败，原因：" + checkOrderInfoMap_msg);
					}
	                Util.waitMoment(Config.getSleepTime() / 30);
	                this.rob.console("验证订单信息...");
					checkOrderInfoMap = this.client.checkOrderInfo(randCode, book_token, this.ui, train, passengers, leftTicketStr, tourFlag);
					checkOrderInfoMap_errMsg = checkOrderInfoMap.get("errMsg");
					checkOrderInfoMap_msg = checkOrderInfoMap.get("msg");
					checkOrderInfoMap_checkHuimd = checkOrderInfoMap.get("checkHuimd");
					checkOrderInfoMap_check608 = checkOrderInfoMap.get("check608");
					this.rob.reset(false);
				}
		        beginTime = System.currentTimeMillis();
				if(!"Y".equals(checkOrderInfoMap_errMsg)) {
					if(checkOrderInfoMap_errMsg != null && checkOrderInfoMap_errMsg.contains("无票") || checkOrderInfoMap_errMsg.contains("没有足够的票")) {
						// 加入黑名单
						if (!this.rob.getBlackTrainCodes().contains(train.getTrain_code())) {
							this.rob.setBlackTrainCodes(this.rob.getBlackTrainCodes() + "|" + train.getTrain_code());
							this.ui.setBlackTrainCodes(this.rob.getBlackTrainCodes());
						}
						this.rob.console("没有足够的票，加入黑名单，重新开始查询车次...");
					}
                    this.rob.reset(false);
					continue;
				} else if("N".equals(checkOrderInfoMap_checkHuimd)) {
					this.rob.reset(true);
					break;
				}
				this.rob.console("查询等待队列...");
				Map<String, String> getQueueCountMap = this.client.getQueueCount(this.ui, train, leftTicketStr);
				boolean op_2 = Boolean.valueOf(getQueueCountMap.get("op_2"));
				boolean op_1 = Boolean.valueOf(getQueueCountMap.get("op_1"));
				int count = Integer.parseInt(getQueueCountMap.get("count"));
				int countT = Integer.parseInt(getQueueCountMap.get("countT"));
				String queue_note = "尊敬的旅客，本次列车您选择的席别尚有余票"+Util.getTicketCountDesc(leftTicketStr,this.ui.getSeat())+"，";
				if(op_2) {
					queue_note += "目前排队人数已经超过余票张数，请您选择其他席别或车次，特此提醒。";
					//queue_note = "今日已有[" + count + "]人先于您提交相同的购票需求，目前排队人数已超过剩余票数，请您选择其他席别或车次。";
					this.rob.console(queue_note);
					// 加入黑名单
					if (!this.rob.getBlackTrainCodes().contains(train.getTrain_code())) {
						this.rob.setBlackTrainCodes(this.rob.getBlackTrainCodes() + "|" + train.getTrain_code());
						this.ui.setBlackTrainCodes(this.rob.getBlackTrainCodes());
					}
					this.rob.console("没有足够的票，加入黑名单，重新开始查询车次...");
                    this.rob.reset(false);
					continue;
				} else {
					if(countT > 0) {
						queue_note += "目前排队人数已经超过["+countT+"]人，";
					}
					queue_note += "特此提醒。";
				}
				/*
				else if(op_1){
					queue_note += "目前排队人数已经超过余票张数，特此提醒。";
					//queue_note = "今日已有[" + count + "]人先于您提交相同的购票需求，到处理您的需求时可能已无票，建议你们根据当前余票确定是否排队。";
				}
				*/
				this.rob.console(queue_note);
				this.rob.console("候选席别为:" + Constants.getTrainSeatName(seatType));

				// for test
                /*if(true){
                    this.rob.console("循环测试中...");
                    if(true) {
                        continue;
                    }
                }*/
				
				// second step
				//Map<String, String> ajaxSubmitOrderMap = this.client.confirmSingleForQueueOrder(randCode, book_token, this.ui, train, passengers, leftTicketStr);
				//String ajaxSubmitOrder_errMsg = ajaxSubmitOrderMap.get("errMsg");
				//if (!"Y".equals(ajaxSubmitOrder_errMsg)) {
				//	this.rob.console("处理失败，原因：" + ajaxSubmitOrder_errMsg);
				//	rs = getResultByMsg(ajaxSubmitOrder_errMsg);
				//	if (Result.RAND_CODE_ERROR == rs.getState()) {
				//		this.rob.console("刷新验证码...");
				//		randCode = getRandCodeDailog(Constants.PassCode_Randp_URL, 4);
				//	}
                endTime = System.currentTimeMillis();
                if (endTime - beginTime < 900) {
                    Util.waitMoment(900 - (endTime - beginTime)); // 此处停留1s
                }
                this.rob.console("进入排队等候...");
                // mark 其实这个地方才是真正排队订票，后面都不用跑了，这个过了就订到票了 (还是走后面的吧，正规点)
				Map<String, String> confirmSingleForQueueMap = this.client.confirmSingleForQueue(randCode, book_token, this.ui, train, passengers, leftTicketStr);
				//String confirmSingleForQueue_Location = confirmSingleForQueueMap.get("Location");
				String confirmSingleForQueue_errMsg = confirmSingleForQueueMap.get("errMsg");
                /*if ((confirmSingleForQueue_errMsg == null || "".equals(confirmSingleForQueue_errMsg)) && confirmSingleForQueue_Location != null
                        && "".equals(confirmSingleForQueue_Location) && confirmSingleForQueue_Location.contains(Constants.SUBMIT_dc_Queue_Location)) {
                    this.rob.console("下单失败！网络忙，请稍后再试...");
                    this.rob.reset(false);
                    continue;
                } else */
                if (!"Y".equals(confirmSingleForQueue_errMsg)) {
					this.rob.console("处理失败，原因：" + confirmSingleForQueue_errMsg);
					if(confirmSingleForQueue_errMsg.contains("包含未付款订单")) {
	                    this.rob.reset(true);
	                    break;
					} else {
    					//rs = getResultByMsg(confirmSingleForQueue_errMsg);
    					//if (Result.RAND_CODE_ERROR == rs.getState()) {
    					//	this.rob.console("刷新验证码...");
    					//	randCode = getRandCodeDailog(Constants.PassCode_Randp_URL, 4);
    					//}
	                    this.rob.reset(false);
                        continue;
					}
				}
				
				/*else {
					this.rob.console("查询订单...");
					rs = this.client.queryOrder();
					this.rob.console(rs.getMsg());
					if (rs.getState() == Result.HAVE_NO_PAY_TICKET) {
						this.orderTicketSucc();
						this.rob.reset(true);
						break;
					}
				}

				// for test TODO 不进入一下循环，多余
                if(true){
                    this.rob.console("循环测试中...");
                    if(true) {
                        continue;
                    }
                }*/
				
				 else {
					int dispTime = 1;
					int nextRequestTime = 1;
					boolean isFinished = false;
					int waitCount = 0; // 等待计数
					String orderId = "";
					while (waitCount < 100 && !isFinished && (isLoginSuc) && (!this.isEnd)) {
						/*if(dispTime == nextRequestTime) {
							Map<String, String> orderWaitTime_Map = this.client.orderWaitTime(this.ui, train, "dc");
							dispTime = Integer.parseInt(orderWaitTime_Map.get("waitTime"));
							int flashWaitTime = dispTime / 2;
							flashWaitTime = flashWaitTime > 30 ? 30 : flashWaitTime;
							int nextTime = dispTime - flashWaitTime;
							nextRequestTime = nextTime <= 0 ? 1 : nextTime;
							orderId = orderWaitTime_Map.get("orderId");
							this.rob.console("==orderId: " + orderId);
						}
						waitFunc("dc", dispTime > 1 ? --dispTime : 1, formatSecondToTime(dispTime));
						if (dispTime <= 0) {
							isFinished = true;
							rs = this.client.finishFunSubmitOrder(randCode, token, this.ui, train, leftTicketStr, Referer, orderId);
						}*/
						// 在此加速抢票
		                this.rob.console("获取订单号...");
						Map<String, String> orderWaitTime_Map = this.client.queryOrderWaitTime(tourFlag);
						orderId = orderWaitTime_Map.get("orderId");
						String orderWaitTime_msg = orderWaitTime_Map.get("msg");
                        if (orderId != null && !"".equals(orderId)) {
                            this.rob.console("订单号 :" + orderId);
                        }
						if (orderId != null && !"".equals(orderId)) {
							isFinished = true;
	                        this.rob.console("生成订单...");
							rs = this.client.finishFunSubmitOrder(randCode, book_token, this.ui, train, passengers, leftTicketStr, orderId);
						} else if (orderWaitTime_msg != null && orderWaitTime_msg.contains("没有足够的票")) {
							waitCount = 100;
							// 加入黑名单
							if (!this.rob.getBlackTrainCodes().contains(train.getTrain_code())) {
								this.rob.setBlackTrainCodes(this.rob.getBlackTrainCodes() + "|" + train.getTrain_code());
								this.ui.setBlackTrainCodes(this.rob.getBlackTrainCodes());
							}
							this.rob.console("没有足够的票，加入黑名单，重新开始查询车次...");
						}
						Util.waitMoment(Config.getSleepTime() / 30);
						this.rob.reset(false);
						waitCount++;
					}
					if(!isFinished) {
						continue;
					}
				}
				this.rob.console(rs.getMsg());
				if (rs.getState() == Result.CANCEL_TIMES_TOO_MUCH) {
					JOptionPane.showMessageDialog(this.rob.getFrame(), "由于您取消次数过多，今日将不能继续受理您的\n订票请求,如需购票请更换账号重新登录");
					this.rob.reset(true);
					break;
				}
				if (rs.getState() == Result.REPEAT_BUY_TICKET) {
					JOptionPane.showMessageDialog(this.rob.getFrame(), "购票人已经买过票了，请更换购票人信息");
					this.rob.reset(true);
					break;
				}
				if (rs.getState() == Result.ERROR_CARD_NUMBER) {
					String info = "请输入购票人正确的身份证号码，以便程序继续尝试！";
					this.rob.console(info);
					this.rob.reset(true);
					continue;
				}
                if (rs.getState() == Result.SUCC && rs.getMsg().contains("订单信息")) {
                    this.orderTicketSucc();
                } else {
                    this.rob.console("查询订单...");
                    rs = this.client.queryOrder();
                    this.rob.console(rs.getMsg());
                    if (rs.getState() == Result.HAVE_NO_PAY_TICKET) {
                        this.orderTicketSucc();
                    }
                }
			}
		}
		this.rob.console("订票逻辑结束");
	}
	
	public void logCookies() {
		this.rob.console("浏览器链接地址 :" + Constants.Login_Otsweb_URL);
		String cookiesMsg = "cookies信息 : javascript:";
		String[] cookiearr = this.cookies.split("\\$");
		for (String cookie : cookiearr) {
			if (cookie != null && !"".equals(cookie)) {
				cookiesMsg = cookiesMsg + "document.cookie='" + cookie + "';";
			}
		}
		cookiesMsg = cookiesMsg + "document.cookie='" + Constants.Temp_Cookie + "';";
		this.rob.console(cookiesMsg);
	}
	
	public void orderTicketSucc() {
        this.logCookies();
        JOptionPane.showMessageDialog(this.rob.getFrame(), "恭喜您订票成功，请在45min内登录www.12306.cn完成付款操作");
        this.rob.reset(true);
	}

	public String getRandCodeDailog(String url, int len) {
		url =url + "&" + Math.random();
		byte[] image = this.client.getCodeByte(url);
		String randCodeByRob = OCR.read(image);
		if (!Constants.ISAUTOCODE) {
			JLabel label = new JLabel(new ImageIcon(), 0);
			label.setIcon(new ImageIcon(image));
			label.setText(" 自动识别为:" + randCodeByRob);
			CodeMouseAdapter cma = new CodeMouseAdapter(randCodeByRob, url);
			label.addMouseListener(cma);
			//String input = (String) JOptionPane.showInputDialog(this.rob.getFrame(), label, "请输入验证码", JOptionPane.PLAIN_MESSAGE, null, null, randCodeByRob);
			String input = JOptionPane.showInputDialog(this.rob.getFrame(), label, "请输入验证码", JOptionPane.PLAIN_MESSAGE);
			if ((input == null) || (input.isEmpty()))
				randCodeByRob = cma.getRandCodeByRob();
			else {
				randCodeByRob = input;
			}
		}
		if (randCodeByRob == null || randCodeByRob.length() != len) {
			if (Constants.ISAUTOCODE) {
				Util.waitMoment(Config.getSleepTime() / 30);
			}
			randCodeByRob = getRandCodeDailog(url, len);
		}
		return randCodeByRob;
	}
	
	public void waitFunc(String tourFlag, long return_time, String show_time) {
		if (return_time < 5) {
			this.rob.console("您的订单已经提交，马上处理完成，请耐心等待。");
		} else if (return_time > 30 * 60) {
			this.rob.console("您的订单已经提交，预计处理时间将大于30分钟，请到未完成订单等待处理结果。");
		} else {
			this.rob.console("您的订单已经提交，预计" + show_time + "处理完成，请耐心等待。");
		}
	}
	
	public String formatSecondToTime(long dispTime) {
		long second = dispTime;
		String show_time = "";
		long hour = second / 3600; // 时
		if (hour > 0) {
			show_time = hour + "小时";
			second = second % 3600;
		}
		long minute = second / 60; // 分
		if (minute >= 1) {
			show_time = show_time + minute + "分";
			second = second % 60;
		} else if (hour >= 1 && second > 0) {
			show_time = show_time + "0分";
		}
		if (second > 0) {
			show_time = show_time + second + "秒";
		}
		return show_time;
	}
	
	public Result getResultByMsg(String msg) {
		Result rs = new Result();
		String ans = msg;
		if(ans == null) {
			rs.setState(Result.OTHER);
			rs.setMsg(ans);
		} else {
			if (ans.isEmpty()) {
				rs.setState(Result.SUCC);
				rs.setMsg("好像订票成功了");
			} else if (ans.contains("由于您取消次数过多")) {
				rs.setState(Result.CANCEL_TIMES_TOO_MUCH);
				rs.setMsg(ans);
			} else if (ans.contains("验证码不正确") || ans.contains("验证码错误")) {
				rs.setState(Result.RAND_CODE_ERROR);
				rs.setMsg(ans);
			} else if (ans.contains("售票实行实名制")) {
				rs.setState(Result.REPEAT_BUY_TICKET);
				rs.setMsg(ans);
			} else if (ans.contains("号码输入有误")) {
				rs.setState(Result.ERROR_CARD_NUMBER);
				rs.setMsg(ans);
			} else if (ans.contains("当前提交订单用户过多")) {
				rs.setState(Result.CURRENT_USER_SOMANY);
				rs.setMsg(ans);
			} else {
				rs.setState(Result.OTHER);
				rs.setMsg(ans);
			}
		}
		return rs;
	}

	public UserInfo getUi() {
		return this.ui;
	}

	public void setUi(UserInfo ui) {
		this.ui = ui;
	}

	public TrainClient getClient() {
		return this.client;
	}

	public void setClient(TrainClient client) {
		this.client = client;
	}

	public boolean setEnd(boolean isEnd) {
		return this.isEnd = isEnd;
	}

	public boolean isLoginSuc() {
		return isLoginSuc;
	}

	public String getUsername() {
		return username;
	}

	public void setUserName(String username) {
		this.username = username;
	}

	public String getCookies() {
		return cookies;
	}

	public void setCookies(String cookies) {
		this.cookies = cookies;
	}

	class CodeMouseAdapter extends MouseAdapter {
		private String randCodeByRob;
		private String url;

		public CodeMouseAdapter(String randCodeByRob, String url) {
			this.randCodeByRob = randCodeByRob;
			this.url = url;
		}

		public void mouseClicked(MouseEvent e) {
			// byte[] image = LogicThread.this.client.getCodeByte(Constants.ORDER_CODE_URL);
			byte[] image = LogicThread.this.client.getCodeByte(this.url);
			this.randCodeByRob = OCR.read(image);
			JLabel label = (JLabel) e.getSource();
			label.setIcon(new ImageIcon(image));
			label.setText(" 自动识别为:" + this.randCodeByRob);
		}

		public String getRandCodeByRob() {
			return this.randCodeByRob;
		}
	}
}
